package com.aijk.commons.idworker;

import com.aijk.commons.cache.RedisConst;
import com.aijk.commons.exception.ErrorCodeConst;
import com.aijk.commons.exception.ErrorCodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

/**
 * <p>  循环ID生成器 </p>
 * User: chendw
 * Date: 2016/9/18 15:32
 */
@Component
public class LoopIdGenerator {

    @Autowired(required = false)
    private JedisCluster jedisCluster;

    /**
     * 循环ID生成器，每天0点重置为0
     *
     * @param key 前缀
     * @return
     */
    public synchronized long nextDayId(String key) {
        if (jedisCluster == null) {
            throw new ErrorCodeException(ErrorCodeConst.GLOBAL_REQCHK_ERROR, "未配置缓存服务");
        }

        long id = jedisCluster.decr(key);

        if (id == 1) { // 生成第一个ID
            jedisCluster.expire(key, RedisConst.EXPIRY_ONE_DAY);
        }
        return id;
    }

}
